package org.urchr.beorganized.api.impl.file;

import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.urchr.beorganized.api.base.BaseAPIServlet;
import org.urchr.beorganized.api.base.PrivateBaseAPIServlet;
import org.urchr.beorganized.dao.NotesDAO;
import org.urchr.beorganized.dao.XMLDocumentBuilder;
import org.urchr.beorganized.dao.errors.GeneralException;
import org.urchr.beorganized.dao.errors.UploadFailedException;

public class Upload extends BaseAPIServlet {

	public Upload() {
		skipBody = true;
	}
	
	@Override
	protected void doProcess() throws GeneralException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		try {
			if(isMultipart){
	    		FileItemFactory factory = new DiskFileItemFactory();
	    		ServletFileUpload upload = new ServletFileUpload(factory);
	    			List<FileItem> multipartItems = upload.parseRequest(request);
	    			int noteID = -1;
	    			String token = null;
	    			FileItem file = null;
					for (FileItem item : multipartItems) {
						if("noteid".equals(item.getFieldName())){
							noteID = NotesDAO.safeInt(item.getString(), -1);
						}
						if("token".equals(item.getFieldName())){
							token = item.getString();
						}
						if("file".equals(item.getFieldName()) && !item.isFormField()){
							file = item;
						}
					}
	//				System.out.println("noteID: "+noteID+", token: "+token+", file: "+file);
					if(noteID!=-1 && token!=null && file!=null){
						int userID = PrivateBaseAPIServlet.checkToken(token);
						if(userID!=-1){
							NotesDAO.uploadData(noteID, userID, file.get(), file.getName(), 
									(int)file.getSize(), file.getContentType());
							XMLDocumentBuilder doc = new XMLDocumentBuilder();
							doc.getRootElement("ok").appendChild(doc.createElement("ok2"));
							sendNode(doc.getRootElement());
							return;						
						}
					}
			}else{
				//Upload text file
				int noteID = NotesDAO.safeInt(request.getParameter("noteid"), -1);
				String token = request.getParameter("token");
				String data = request.getParameter("data");
				int userID = PrivateBaseAPIServlet.checkToken(token);
				if(userID!=-1 && noteID!=-1){
					NotesDAO.uploadData(noteID, userID, data==null?null:data.getBytes("utf-8"), null, 0, null);
					XMLDocumentBuilder doc = new XMLDocumentBuilder();
					doc.getRootElement("ok").appendChild(doc.createElement("ok2"));
					sendNode(doc.getRootElement());
					return;						
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new UploadFailedException();
		}
	}

}
